package cn.edu.hnu.gpg.controller;

import cn.edu.hnu.gpg.api.error.NotFoundException;
import cn.edu.hnu.gpg.api.error.PermissionDeniedException;
import cn.edu.hnu.gpg.dto.PhaseWithDocInfo;
import cn.edu.hnu.gpg.dto.StudentDocumentInfo;
import cn.edu.hnu.gpg.entity.*;
import cn.edu.hnu.gpg.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    private final Logger logger = LogManager.getLogger(UserController.class);

    private final TeacherService teacherService;
    private final QuestionService questionService;
    private final SupervisionService supervisionService;
    private final StudentService studentService;
    private final StudentDocService studentDocService;
    private final PlanService planService;
    @Autowired
    public TeacherController(TeacherService teacherService, QuestionService questionService, SupervisionService supervisionService, StudentService studentService, StudentDocService studentDocService, PlanService planService){
        this.teacherService = teacherService;
        this.questionService = questionService;
        this.supervisionService = supervisionService;
        this.studentService = studentService;
        this.studentDocService = studentDocService;
        this.planService = planService;
    }

    @RequestMapping("/change_password")
    public String ChangePassword() {
        return "jsp/teacher/change_teacherpw.jsp";
    }

    @RequestMapping("/search_question")
    public String SearchQuestion(HttpServletRequest request, Map<String,Object> model){
        User user =(User)request.getSession(true).getAttribute("user");
        Teacher teacher = teacherService.findTeacherByUserId(user.getUserId());
        List<Integer> studentList = supervisionService.findStudentIdByTeacher(teacher);
        if (studentList == null)
            return "jsp/teacher/do_answer404.jsp";
        List<Question> questions = new ArrayList<>();
        for (Integer id : studentList){
            List<Question> questionforstudent = questionService.findQuestionByStudentId(id);
            if (questionforstudent!=null)
                questions.addAll(questionforstudent);
        }
        //System.out.println(questions.get(0).getDescription());
        model.put("questions", questions);
        logger.info(questions.size());
        return "jsp/teacher/do_answer.jsp";
    }

    @RequestMapping("/manager_student")
    public String SearchStudent(){
        return "jsp/teacher/modify_student.jsp";
    }

    @RequestMapping("/group_message")
    public String toGroupMessage(HttpServletRequest request, Map<String, Object> model) {
        User user = ((User) request.getSession().getAttribute("user"));
        Teacher teacher = teacherService.findTeacherByUserId(user.getUserId());

        List<Supervision> supervisionList = supervisionService.findSupervisionByTeacherId(teacher);
        if (supervisionList == null)
            supervisionList = new ArrayList<>();
        List<Student> studentList = new ArrayList<>(supervisionList.size());

        for (Supervision s :
                supervisionList) {
            Student student = studentService.findStudentByStudentId(s.getStudentId());
            if (student != null)
                studentList.add(student);
        }

        model.put("studentList", studentList);

        return "jsp/teacher/group_message.jsp";
    }

    @RequestMapping(value = "/student_progress", method = RequestMethod.GET)
    public String toStudentProgress(HttpServletRequest request, Map<String, Object> model,
                                    @RequestParam(name = "student_id", required = false) Integer studentId) throws NotFoundException, PermissionDeniedException {
        User user = ((User) request.getSession().getAttribute("user"));
        Teacher teacher = teacherService.findTeacherByUserId(user.getUserId());

        if (studentId != null) {
            Student student = studentService.findStudentByStudentId(studentId);

            if (student == null)
                throw new NotFoundException("Student requested not found");
            Integer teacherId = supervisionService.findTeacherByStudent(student);
            if (!teacherId.equals(teacher.getTeacherId()))
                throw new PermissionDeniedException("The student specified is not under your supervision");

            List<StudentDocumentInfo> documentInfoList = studentDocService.listDocumentByStudentId(studentId);
            List<Plan> planList = planService.listPlans();

            List<PhaseWithDocInfo> phaseList = new ArrayList<>(planList.size());
            for (Plan p : planList) {
                PhaseWithDocInfo phase = new PhaseWithDocInfo();
                phase.setPlan(p);
                phaseList.add(phase);
            }

            Iterator<PhaseWithDocInfo> iterator = phaseList.iterator();
            PhaseWithDocInfo phase = iterator.next();

            if (documentInfoList != null) {
                for (StudentDocumentInfo docInfo : documentInfoList) {
                    while (phase.getPlan().getPhaseId() < docInfo.getPhaseId() && iterator.hasNext()) {
                        phase = iterator.next();
                    }
                    phase.setDocumentInfo(docInfo);
                }
            }

            model.put("student", student);
            model.put("phaseList", phaseList);

            return "jsp/teacher/student_progress_detail.jsp";
        }

        List<Integer> studentIdList = supervisionService.findStudentIdByTeacher(teacher);
        List<Student> studentList;
        studentList = studentService.findStudentByStudentId(studentIdList);
        model.put("studentList", studentList);

        return "jsp/teacher/student_progress.jsp";
    }
}
